//
//  SEGElevatorControlViewModel.m
//  SEGViewModel
//
//  Created by 乔杨 on 2020/6/16.
//

#import "SEGElevatorControlViewModel.h"
#import "SEGElevatorControlManager.h"
#import "SEGWangLongTKManager.h"

// 电梯设备用户ID。目前与后台商定写死为此值。用户密钥keyU后台传回,配套使用。
static NSString *const kElevatorUserId = @"88888888";

@interface SEGElevatorControlViewModel ()

@property (nonatomic, strong) SEGElevatorControlManager *elevatorControlManager;
@property (nonatomic, strong) SEGWangLongTKManager *wangLongTKManager;
/// 用于搜索电梯设备的数据数组
@property (nonatomic, copy) NSArray *elevatorArray;
// 用于判断蓝牙状态
@property (nonatomic, strong) CBPeripheralManager *peripheralManager;

@end

@implementation SEGElevatorControlViewModel

- (instancetype)init {
    self = [super init];
    if (!self) return nil;
    [self seg_createElevatorListSignal];
    [self seg_createQrCodeCommand];
    [self seg_createCallElevatorCommand];
    return self;
}
- (void)seg_createElevatorListSignal {
    @weakify(self);
    self.listSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        [self.elevatorControlManager requestElevatorControlWithCommunityId:kAccountCommunityID finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            self.dataArr = self.elevatorControlManager.dataArr;
            [subscriber sendNext:@""];
            [subscriber sendCompleted];
        }];
        return nil;
    }];
}
- (void)seg_createQrCodeCommand {
    @weakify(self);
    self.qrCodeCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(RACTuple *tuple) {
        RACTupleUnpack(NSString *elevId, NSString *floor, NSString *directionFlag) = tuple;
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            [self.elevatorControlManager getElevGroupQrCodeWithElevId:elevId floor:floor directionFlag:directionFlag extDate:@"" openNum:@"" finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                self.qrCodeStr = self.elevatorControlManager.qrCodeStr;
                [subscriber sendNext:@(isSuccessed)];
                [subscriber sendCompleted];
            }];
            
            return nil;
        }];
    }];
}
- (void)seg_createCallElevatorCommand {
    @weakify(self);
    self.callElevatorCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(RACTuple *tuple) {
        RACTupleUnpack(SEGFloorsModel *ret, NSString *elevId, NSString *elevType, NSString *keyU) = tuple;
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            if ([elevType isEqualToString:@"0"]) { // 蓝牙
                // 判断蓝牙状态
                [self peripheralManager];
                [[RACScheduler mainThreadScheduler] afterDelay:0.5 schedule:^{
                    if (self.peripheralManager.state == CBPeripheralManagerStatePoweredOn) {
                        // 开始呼叫电梯
                        [subscriber sendNext:@(SEGOpenDoorStatus_Begin)];
                        
                        // 楼层选择最多能够支持两层。目前为一层，如果要改成两层，需要配置好楼层数据add到selectFloors数组
                        NSMutableArray *selectFloors = [NSMutableArray array];
                        // 选择楼层数据配置
                        [selectFloors addObject:@[ret.floor, ret.directionFlag]];
                        // 电梯内呼叫数组配置处理
                        //openFloors的第1、2个元素表示常用楼层，即呼梯楼层，最多支持两个楼层，bit0-6表示楼层，bit7表示0代表正门，1代表背门。openFloors的第3个元素表示有权限楼层数目，openFloors的第3到第10个元素表示有权限的楼层
                         NSArray *floorNums = [self.wangLongTKManager getfloorswith:selectFloors and:self.floorArray];
                        [self.wangLongTKManager callElevatorWith:self.elevatorArray userId:kElevatorUserId keyU:keyU floorNums:floorNums callBack:^(SEGOpenDoorStatus status, NSDictionary *dict) {
                            if (status == SEGOpenDoorStatus_Success) {
                                if ([[SEGUtils ValueToString:dict[@"code"]] isEqualToString:@"0"]) { // 呼梯成功
                                    [subscriber sendNext:@(SEGOpenDoorStatus_Success)];
                                    [subscriber sendCompleted];
                                } else { // 呼梯失败
                                    [subscriber sendNext:@(SEGOpenDoorStatus_Failed)];
                                    [subscriber sendCompleted];
                                }
                            } else { // 失败（包含搜索失败，校验失败等等）
                                [subscriber sendNext:@(SEGOpenDoorStatus_Failed)];
                                [subscriber sendCompleted];
                            }
                        }];
                    } else {
                        NSError *error = [NSError errorWithDomain:@"" code:self.peripheralManager.state userInfo:@{NSLocalizedFailureReasonErrorKey:@""}];
                        [subscriber sendError:error];
                    }
                }];
            } else { // 二维码
                self.codeElevId = elevId;
                self.codeFloor = ret.floor;
                self.codeDirectionFlag = ret.directionFlag;
                [subscriber sendNext:@""];
                [subscriber sendCompleted];
            }
            
            return nil;
        }];
    }];
}
- (void)seg_generatLevatorArrayForScanWithElevTag:(NSString *)elevTag {
    NSMutableArray *dataArr = [NSMutableArray array];
    NSArray *devUniqueArray = [ elevTag componentsSeparatedByString:@","];
    for (NSString *devUnique in devUniqueArray) {
        NSDictionary *dic = @{@"devType" : @"1",//电梯类型“1”
                              @"standardValue" : @"85",//修正值80~90
                              @"devUnique" : CHECKVALUE(devUnique)//电梯设备唯一码
                              };
        [dataArr addObject:dic];
    }
    self.elevatorArray = dataArr;
}

#pragma mark - Getter
- (SEGElevatorControlManager *)elevatorControlManager {
    if (!_elevatorControlManager) _elevatorControlManager = [[SEGElevatorControlManager alloc] init];
    return _elevatorControlManager;
}
- (SEGWangLongTKManager *)wangLongTKManager {
    if (!_wangLongTKManager) _wangLongTKManager = [[SEGWangLongTKManager alloc] init];
    return _wangLongTKManager;
}
- (CBPeripheralManager *)peripheralManager {
    if (!_peripheralManager) _peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:nil queue:nil options:@{CBCentralManagerOptionShowPowerAlertKey:@(NO)}];
    return _peripheralManager;
}

@end
